package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"
	"zy5_novel/cache"
	"zy5_novel/models"
)

type NovelController struct {
	beego.Controller
}

func (c *NovelController) Create() {
	var err error

	title := c.GetString("title")
	author := c.GetString("author")
	images := c.GetString("images")
	userId, _ := c.GetInt("user_id")

	var novel models.Novel
	novel.Title = title
	novel.Author = author
	novel.Images = images
	novel.UserId = userId

	if err = novel.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "小说发布失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "小说发布成功",
	}
	c.ServeJSON()
}

func (c *NovelController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var err error
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")
	var novel models.Novel
	var list []models.Reads

	key := fmt.Sprintf("list_%d_%d", page, pageSize)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheData != "" {
		json.Unmarshal([]byte(cacheData), &list)
	} else {
		list, _ = novel.List(page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour)
		}
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "小说列表查询失败",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&models.Novel{}).Count(&count)

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "小说列表查询成功",
		"data":    list,
		"count":   count,
	}
	c.ServeJSON()
}

func (c *NovelController) Upload() {
	file, m, err := c.GetFile("image")
	if err != nil {
		return
	}
	openFile, _ := os.OpenFile("static/img/"+m.Filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
	io.Copy(openFile, file)
	fmt.Println(file, m, err)

	ext := filepath.Ext(m.Filename)
	suffix := ".jpg.png.jpeg"

	if !strings.Contains(suffix, ext) {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "上传失败，图片格式只能为.jpg .png .jpeg",
		}
		c.ServeJSON()
		return
	}

	if m.Size >= 1204*1204*2 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "上传失败，图片大小只能为2MB",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "图片上传成功",
		"data":    "http://127.0.0.1:8084/static/img/" + m.Filename,
	}
	c.ServeJSON()
}
func (c *NovelController) Delete() {
	var err error

	id, _ := c.GetInt("id")
	var novel models.Novel
	novel.ID = uint(id)

	novel.GetAccountById()
	if novel.Status == "已完成" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "已完成阅读的记录禁止删除",
		}
		c.ServeJSON()
		return
	}

	if err = novel.Del(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "删除失败",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("news_deleteid_%d", novel.ID)
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "删除成功",
	}
	c.ServeJSON()
}
